import 'package:flutter/widgets.dart';
import 'package:flutter_app/tools/http.dart';
import 'package:flutter_app/model/tweet.dart';
import 'tweet_grid_item.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/common/global.dart';
import 'tweet_add_view.dart';
import 'package:flutter_app/tools/utils.dart';
import 'package:flutter_app/tools/widget.dart';
// import 'package:pull_to_refresh/pull_to_refresh.dart';

class TweetListView extends StatefulWidget {
  TweetListView({Key key}) : super(key: key);

  @override
  _TweetListViewState createState() => _TweetListViewState();
}

class _TweetListViewState extends State<TweetListView>
    with AutomaticKeepAliveClientMixin {
  int p = 0; //
  String refreshTime; //刷新时间
  List<Tweet> tweetList = [];
  bool noMore = false; //没有更多

  bool isLoading = false; //是否正在加载数据

  ScrollController _controller = new ScrollController(); //上拉加载更多控制器

  GlobalKey<RefreshIndicatorState> _indicatorKey =
      GlobalKey<RefreshIndicatorState>(); //下拉刷新控件

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    _onRefresh();

    //监听滑动到最底部
    // _controller.addListener(() {
    //   // print(_controller.position.pixels.toString() +
    //   //     "|" +
    //   //     _controller.position.maxScrollExtent.toString());
    //   if (_controller.position.pixels == _controller.position.maxScrollExtent) {
    //     getTweetList();
    //   }
    // });
  }

//获取tweet列表根据页号
  getTweetList() async {
    if (!isLoading) {
      isLoading = true;
      p += 1;
      if (p == 1) {
        tweetList = [];
        refreshTime = m_utils.formartDateTimeToSecond(DateTime.now());
        noMore = false;
      }
      if (!noMore) {
        final lb = await Global.loadBalancer;
        List<Tweet> resultList = await lb
            .run<List<Tweet>, Map<String, dynamic>>(m_http.getTweetList,
                {"p": p, "refreshTime": refreshTime, "userId": Global.userId});
        // resultList = await lb.run<List<Tweet>, Map>(m_http.tweetIsLiked,
        //     {"tweetList": resultList, "userId": Global.userId});
        if (resultList.length > 0) {
          tweetList.addAll(resultList);
        } else {
          noMore = true;
        }

        // setState(() {});
      }
      isLoading = false;
    }
    setState(() {});
  }

  //下拉重新刷新
  Future<Null> _onRefresh() async {
    p = 0;
    await getTweetList();
    await Future.delayed(Duration(milliseconds: 2000), () {});
  }

  Widget getRow([Tweet tweet]) {
    return new TweetGridItem(
      tweet: tweet,
      key: UniqueKey(), //必须要有key 不然setState时listView可能不刷新
    );
  }

  //跳转到添加动态
  Function jumpToTweetAddView = (BuildContext context) {
    Navigator.push(context, MaterialPageRoute(builder: (_) {
      return new TweetAddView();
    }));
  };

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Stack(children: [
      RefreshIndicator(
        key: _indicatorKey,
        child: ListView.builder(
          scrollDirection: Axis.vertical,
          physics: const AlwaysScrollableScrollPhysics(),
          cacheExtent: 0,
          itemCount: tweetList.length + 1,
          itemBuilder: (BuildContext context, int position) {
            if (position < tweetList.length) {
              return getRow(tweetList[position]);
            } else {
              if (_controller.position.haveDimensions &&
                  !_controller.position.outOfRange &&
                  !noMore) {
                Future.delayed(Duration(milliseconds: 200)).then((e) {
                  getTweetList();
                });
              }
              return utilsWidget.loadingWidget(isLoading, noMore);
            }
          },
          controller: _controller,
        ),
        onRefresh: _onRefresh,
      ),

      // ListView(
      //     scrollDirection: Axis.vertical,
      //     physics: BouncingScrollPhysics(),
      //     children: tweetList),
      Positioned(
        right: 30,
        bottom: 30,
        child: Container(
            width: 30,
            height: 30,
            child: Align(
              child: FloatingActionButton(
                tooltip: 'Add', // used by assistive technologies
                heroTag: "Add",
                child: Icon(
                  Icons.add,
                  size: 25.0,
                ),

                onPressed: () {
                  jumpToTweetAddView(context);
                },
              ),
            )),
      ),
      Positioned(
        right: 30,
        bottom: 75,
        child: Container(
            width: 30,
            height: 30,
            child: Align(
              child: FloatingActionButton(
                tooltip: '刷新', // used by assistive technologies
                heroTag: "刷新",
                child: Icon(
                  Icons.refresh,
                  size: 25.0,
                ),

                onPressed: () {
                  // getTweetList();
                  //_indicatorKey.currentState.show();
                  if (_controller.position.pixels > 0) {
                    _controller.jumpTo(0);
                  } else {
                    _indicatorKey.currentState.show();
                  }
                },
              ),
            )),
      )
    ]);
  }
}
